<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Encore\Admin\Traits\ModelTree;
use Encore\Admin\Traits\AdminBuilder;
use Illuminate\Support\Facades\DB;

class Department extends Model
{
    use ModelTree,AdminBuilder;

    protected $fillable = ['name','department_code','description','order', 'parent_id'];

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $this->setParentColumn('parent_id');
        $this->setOrderColumn('order');
        $this->setTitleColumn('name');
    }

    public function users()
    {
        return $this->hasMany(User::class,'department_id');
    }

    public function tasks(){
        return $this->hasMany(Task::class, 'department_id');
    }

    public function records()
    {
        return $this->hasMany(Record::class, 'department_id');
    }

    public function charger()
    {
        return $this->belongsTo(User::class, 'charger_id');
    }

    public static function getAllChildrenId($department_id = 0)
    {
        $department_ids = DB::table('departments')->where('parent_id', '=', $department_id)->pluck('id')->toArray();
        return $department_ids;
    }
}
